package com.taotao.service;

import java.io.IOException;
import java.util.UUID;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.pojo.EUImageUpload;
import com.taotao.utils.FtpUtils;
import com.taotao.utils.IDUtils;

@Service
public class PictureServiceImpl implements PictureService {

	@Value("${FTP_ADDRESS}")
	private String FTP_ADDRESS;

	@Value("${FTP_PORT}")
	private Integer FTP_PORT;

	@Value("${FTP_USERNAME}")
	private String FTP_USERNAME;

	@Value("${FTP_PASSWORD}")
	private String FTP_PASSWORD;

	@Value("${FTP_BASEPATH}")
	private String FTP_BASEPATH;

	@Value("${IMAGE_BASE_URL}")
	private String IMAGE_BASE_URL;

	@Override
	public EUImageUpload uploadPic(MultipartFile uploadFile) {
		// TODO Auto-generated method stub
		// 生成新名字
		// 获取旧名字
		EUImageUpload image = new EUImageUpload();
		String oldName = uploadFile.getOriginalFilename();
		String filePath = new DateTime().toString("/yyyy/MM/dd");

		// 生成姓名子
		String newName = IDUtils.genImageName() + oldName.substring(oldName.indexOf("."));
		try {
			FtpUtils.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASEPATH, filePath, newName,
					uploadFile.getInputStream());
			// FtpUtils.uploadFile("192.168.237.135", 21, "ftptest", "ghl",
			// "/images", "", oldName, uploadFile.getInputStream());
			image.setError(0);
			image.setUrl(IMAGE_BASE_URL + FTP_BASEPATH + filePath + "/" + newName);
			//System.out.println("url: " + image.getUrl());
			return image;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			image.setError(1);
			image.setMessage("上传失败!");
			e.printStackTrace();
		}

		return image;
	}

}
